package hyl.base.ntty.handle;

import java.io.File;
import java.io.FileInputStream;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.FileRegion;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
//把通道内容写入文件
public class CopyBigDataHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	File _savefile ;
	public CopyBigDataHandler (File 保存到 ){
		//File file = new File("test.txt");
		_savefile=保存到;
	}
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
	     if(_savefile==null )return;
		FileInputStream fis = new FileInputStream(_savefile);
		FileRegion region = new DefaultFileRegion(fis.getChannel(), 0, _savefile.length());
		Channel channel = ctx.channel();
		//写入数据并监听是否完成
		channel.writeAndFlush(region).addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (!future.isSuccess()) {
					//Throwable cause = future.cause();
				}
			}
		});
	}
}